package com.smartfactory.sail.controller;


import com.ada.base.common.ApiResponse;
import com.ada.base.common.ControllerResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.smartfactory.sail.config.HeaderWrapper;
import com.smartfactory.sail.config.OperRecord;
import com.smartfactory.sail.constant.header.PurchaseEnum;
import com.smartfactory.sail.entity.Item;
import com.smartfactory.sail.entity.Purchase;
import com.smartfactory.sail.entity.PurchaseRecord;
import com.smartfactory.sail.entity.StorageCurrentInfo;
import com.smartfactory.sail.entity.enums.PurchaseStatusEnum;
import com.smartfactory.sail.entity.enums.PurchaseTypeEnum;
import com.smartfactory.sail.mapper.StorageCurrentInfoMapper;
import com.smartfactory.sail.service.ICustService;
import com.smartfactory.sail.service.IItemService;
import com.smartfactory.sail.service.IPurchaseRecordService;
import com.smartfactory.sail.service.IPurchaseService;
import com.smartfactory.sail.utils.CodeUtils;
import com.smartfactory.sail.utils.DateUtils;
import com.smartfactory.sail.vo.PageParam;
import com.smartfactory.sail.vo.purchase.AddPucharses;
import com.smartfactory.sail.vo.purchase.ListPurchaseResp;
import com.smartfactory.sail.vo.purchase.UploadVoucherReq;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 采购单表 前端控制器
 * </p>
 *
 * @author 王巨壁
 * @since 2019-08-20
 */
@RestController
@RequestMapping("/purchase")
@Api(tags = "采购管理")
public class PurchaseController extends ControllerResponse {

    private IPurchaseService iPurchaseService;
    private IPurchaseRecordService iPurchaseRecordService;
    private IItemService iItemService;
    private StorageCurrentInfoMapper StorageCurrentInfoMapper;
    private ICustService iCustService;

    public PurchaseController(IPurchaseService iPurchaseService, IPurchaseRecordService iPurchaseRecordService, IItemService iItemService, com.smartfactory.sail.mapper.StorageCurrentInfoMapper storageCurrentInfoMapper, ICustService iCustService) {
        this.iPurchaseService = iPurchaseService;
        this.iPurchaseRecordService = iPurchaseRecordService;
        this.iItemService = iItemService;
        StorageCurrentInfoMapper = storageCurrentInfoMapper;
        this.iCustService = iCustService;
    }

    @HeaderWrapper(PurchaseEnum.class)
    @PostMapping("list/{currentPage}/{size}/{sortType}/{sortField}")
    @ApiOperation(value = "采购列表", notes = "采购列表")
    public ApiResponse<IPage<ListPurchaseResp>> list(@RequestBody Map<String, Object> queryParam,
                                                     @PathVariable("currentPage") Long currentPage,
                                                     @PathVariable("size") Integer size,
                                                     @PathVariable("sortType") Integer sortType,
                                                     @PathVariable("sortField") String sortField) {
        PageParam pageParam = new PageParam(currentPage, size, sortType, "pr." + sortField);
        iPurchaseService.getListByPage(queryParam, pageParam);
        return ok(iPurchaseService.getListByPage(queryParam, pageParam));
    }

    @PostMapping("showPurchaseList/{purchaseId}")
    @ApiOperation(value = "根据采购订单获取详情", notes = "根据采购订单获取详情")
    public ApiResponse<List<PurchaseRecord>> showPurchaseList(@PathVariable("purchaseId") Long purchaseId) {
        QueryWrapper<PurchaseRecord> query = new QueryWrapper<>();
        query.eq("purchaseId", purchaseId);
        return ok(iPurchaseRecordService.list(query));
    }

    @OperRecord(content = "填写采购详情",level = 1)
    @PostMapping("perfectPurchase")
    @ApiOperation(value = "完善确认采购单", notes = "完善确认采购单 只有待采购状态才可以修改采购单.")
    public ApiResponse<Boolean> perfectPurchase(@RequestBody List<PurchaseRecord> purchaseRecords) {
        //判断是否已经是待入库状态  待入库之后不允许修改采购信息
        if (purchaseRecords.get(0).getStatus().getCode() > PurchaseStatusEnum.DCG.getCode()) {
            return fail("该状态不允许修改");
        }

        for (PurchaseRecord purchaseRecord : purchaseRecords) {
            purchaseRecord.setStatus(PurchaseStatusEnum.CGZ);
        }
        if (iPurchaseRecordService.updateBatchById(purchaseRecords)) {
            //修改最近合作时间
            Long custId = purchaseRecords.get(0).getSupplierId();
            iCustService.updateCooperationTime(custId, DateUtils.getNowDate());

            Purchase purchase = new Purchase();
            purchase.setId(purchaseRecords.get(0).getPurchaseId());
            purchase.setStatus(PurchaseStatusEnum.CGZ);
            iPurchaseService.updateById(purchase);
        }
        return ok();
    }

    @OperRecord(content = "上传采购凭证",level = 1)
    @PostMapping("uploadVoucher")
    @ApiOperation(value = "批量上传采购凭证", notes = "批量上传采购凭证 多个用|隔开,id是列表返回对象中的id字段")
    public ApiResponse<Boolean> uploadVoucher(@RequestBody @Validated List<UploadVoucherReq> reqs) {
        ArrayList<PurchaseRecord> purchaseRecords = new ArrayList<>();
        for (UploadVoucherReq req : reqs) {
            PurchaseRecord purchaseRecord = new PurchaseRecord();
            purchaseRecord.setId(req.getId());
            purchaseRecord.setImags(req.getImgs());
            purchaseRecords.add(purchaseRecord);
        }
        return ok(iPurchaseRecordService.updateBatchById(purchaseRecords));
    }

    @OperRecord(content = "新增采购",level = 1)
    @PostMapping("add")
    @ApiOperation(value = "新增采购", notes = "新增采购")
    public ApiResponse<Boolean> addPucharses(@RequestBody List<AddPucharses> reqs) {

        List<PurchaseRecord> records = new ArrayList<>();

        for (AddPucharses req : reqs) {
            Purchase purchase = new Purchase();
            purchase.setPurchaseType(PurchaseTypeEnum.BLDD);
            purchase.setObjId(req.getItemId());
            purchase.setStatus(PurchaseStatusEnum.DCG);
            purchase.setCode(CodeUtils.creatCGCode());
            if (iPurchaseService.save(purchase)) {

                PurchaseRecord purchaseRecord = new PurchaseRecord();

                Item item = iItemService.getById(req.getItemId());

                purchaseRecord.setPurchaseId(purchase.getId());
                purchaseRecord.setItemId(item.getId());
                purchaseRecord.setItemCode(item.getCode());
                purchaseRecord.setItemName(item.getName());
                purchaseRecord.setSpecification(item.getSpecification());
                purchaseRecord.setPurchaseSize(req.getSize());
                try {
                    StorageCurrentInfo byItemId = StorageCurrentInfoMapper.getByItemId(item.getId(), 2);
                    if (byItemId != null) {
                        purchaseRecord.setCurrentStorageSize(byItemId.getAllocatableSize());
                    } else {
                        purchaseRecord.setCurrentStorageSize(0);
                    }
                } catch (Exception e) {
                    purchaseRecord.setCurrentStorageSize(0);
                }

                records.add(purchaseRecord);
            }

        }
        if (iPurchaseRecordService.saveBatch(records)) {
            return ok();
        } else {
            return fail("新增失败");
        }
    }
}
